package com.typhoon.spring_jdbctemplate.dao;

import com.typhoon.spring_jdbctemplate.dao.support.CustomJdbcTemplate;
import com.typhoon.spring_jdbctemplate.dao.support.PageQuery;
import com.typhoon.spring_jdbctemplate.dao.support.PageResult;
import com.typhoon.spring_jdbctemplate.entity.Task;
import com.typhoon.spring_jdbctemplate.util.DataSourceUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 任务dao操作层
 *
 */
public class TaskDao {

    private static final String table_task = "Task";

    private CustomJdbcTemplate jdbcTemplate = DataSourceUtils.getCustomJdbcTemplate();

    public PageResult<Task> page(PageQuery pageQuery, Map<String,Object> params) {
        StringBuilder sql = new StringBuilder();
        List<Object> paramList = new ArrayList<>();
        sql.append(" select * from Task where 1 = 1 ");
        Object id = params.get("id");
        if(null != id) {
            sql.append(" and ").append(" id =?  ");
            paramList.add(id);
        }
        Object status = params.get("status");
        if(null != status) {
            sql.append(" and  ").append("	status = ?	");
            paramList.add(status);
        }

        sql.append("  order by createTime desc  ");

        return this.jdbcTemplate.page(sql.toString(), BeanPropertyRowMapper.newInstance(Task.class), pageQuery, paramList.toArray());
    }

    public int update(Task task) {

        StringBuilder sql = new StringBuilder();
        List<Object> paramList = new ArrayList<>();
        sql.append(" update Task set ");
        Object status =task.getStatus();
        if(null != status) {
            sql.append("	status = ?	");
            paramList.add(status);
        }
        sql.append(" where  id = ? ");
        paramList.add(task.getId());
        return  this.jdbcTemplate.update(sql.toString(),paramList.toArray());
    }

    public int insert(Task task) {
        StringBuilder sql = new StringBuilder();
        List<Object> paramList = new ArrayList<>();
        sql.append("insert into Task values(null, ");
        Object status =task.getStatus();
        sql.append(" ?,	");
        paramList.add(status);
        sql.append(" now()) ");
        return  this.jdbcTemplate.update(sql.toString(),paramList.toArray());
    }

}
